package MMSServer;

import java.io.*;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.Date;
import java.util.StringTokenizer;

import DatabaseManager.*;
import HTTPRecieveParser.*;
import HTTPSendIntegrator.*;
import PUSHSendIntegrator.*;

public class PUSHProcess extends Thread {
	
	public static final int PUSH_PORT = 9200;
	
	private static BufferedReader inFromClient = null;
	private static DataOutputStream outToClient = null;
	
	private static final String MMS_MESSAGE_STARTUP_IND = "m-startup-ind";

	public Socket clientSocket; 
	public String clientID;
	
	private String mmsBody;
	private StringTokenizer tokenizedRequestLine;
	private String strContentLength;
	private int contentLength;
	
 private StartupInd startUpIndMsg;
 
 private MMBoxManager mmBoxManager;
 private PushTempBox pushTempBox;
 private UserDBManager userDB;
 private String clientAddr;

 private String [] pduMsg;
 
	PUSHProcess(Socket clientSocket)
	{
		userDB = new UserDBManager();
		mmBoxManager = new MMBoxManager();		
		pushTempBox = new PushTempBox();
		this.clientSocket = clientSocket;
		clientAddr = (clientSocket.getInetAddress()).toString();
	}

	@Override
	public void run() {
		try {
			inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			outToClient = new DataOutputStream(clientSocket.getOutputStream());
			System.out.println("PUSH THREAD START");
			System.out.println("From client message");
			String requestMessageLine = inFromClient.readLine();	//	POST / HTTP/1.1
			System.out.println(requestMessageLine);
			requestMessageLine = inFromClient.readLine();	// Host: 210.107.196.185:9090
			System.out.println(requestMessageLine);
			requestMessageLine = inFromClient.readLine();	// Content-Type: application/vnd.wap.mms-mesage
			System.out.println(requestMessageLine);
			requestMessageLine = inFromClient.readLine(); //	Content-Length: 111111
			System.out.println(requestMessageLine);
			
			tokenizedRequestLine = new StringTokenizer(requestMessageLine); 
			tokenizedRequestLine.nextToken(); //	Content-Length:

			strContentLength = tokenizedRequestLine.nextToken(); // 111111
			contentLength = Integer.parseInt(strContentLength);

			char arr[] = new char[contentLength];
			inFromClient.read(arr);
			mmsBody = new String(arr);
			System.out.println(mmsBody);
			
			// X-Mms-Message-Type: m-startup-ind
			// From: -------

			startUpIndMsg = new StartupInd(mmsBody);
			startUpIndMsg.decodeMessage();
			
			//Save ClientID(E-mail | PhoneNumber | IP-Adress) for sending Push Msg
			clientID = startUpIndMsg.getFrom();

			// User registration.
			userDB.ConnectionDB();
			userDB.UpdateUserAddress(clientID, clientAddr);
			userDB.CloseConnectionDB();
			
			System.out.println("ClientID: " + clientID);
			
			while(clientSocket.isConnected())
			{
					pushTempBox.ConnectDB();
					if(pushTempBox.IsStoredPdu(clientID))
					{
						pduMsg = pushTempBox.GetPduMessage(clientID);
						for(int i=0; i<pduMsg.length; i++)
						{
							SendPOSTMessage(pduMsg[i]);
							System.out.println(pduMsg[i]);
							pushTempBox.DeletePduMessage(pduMsg[i]);
							System.out.println("Push message send!!!");
						}
					}
					pushTempBox.CloseConnectionDB();
					Thread.sleep(12000);
			}
			
			System.out.println("socket end");
				//Noti Search Condition     : reciver, noti
				//Delivery Search Condition : reciver, DeliveryReport, ReceiverDeliveryAllowed==true, SenderDeliveryAllowed==true
				//ReadOrg Search Condition  : reciver, ReadReport, SenderReadAllowed==true, ReceiverReadAllowed == true
				//
				// if!! All of this situation previously was excuted 
				// In PDUMSGBox All of messages that we have to send will exist.
				// Don't need to integrate push message again. just send it~~
				// therefore,,,  
			//}
			
		
		} catch (IOException ioe) {
			System.out.println("socket error");
			ioe.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			//socekt.close();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void SendPOSTMessage(String body) throws IOException
	{
		outToClient.writeBytes("POST" + " " + "/" + " " + "HTTP/1.1" + "\r\n");
		outToClient.writeBytes("Host: " + "210.107.196.205:9000" + "\r\n");
		outToClient.writeBytes("Content-Type: "+ "application/vnd.wap.mms-message" + "\r\n");
		int length = body.length() + 2;
		outToClient.writeBytes("Content-Length: " + length + "\r\n\r\n");
		outToClient.writeBytes(body);
	}
}